package com.sls.game.service.impl;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.ObjectIncreaseId;
import com.sls.core.util.ServerDateAndTime;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.GoodsInfoManageDAO;
import com.sls.game.dao.GoodsSupplyManageDAO;
import com.sls.game.dao.NutsNetGoodsInfoDAO;
import com.sls.game.dao.OhFeiGoodsBrandDAO;
import com.sls.game.dao.OhFeiGoodsInfoDAO;
import com.sls.game.dao.ProductBrandDAO;
import com.sls.game.dao.SpecialPriceSystemDAO;
import com.sls.game.dao.TencentGoodsInfoDAO;
import com.sls.game.page.Pagination;
import com.sls.game.pojo.GoodsManageInfo;
import com.sls.game.pojo.GoodsSupplyManageInfo;
import com.sls.game.pojo.ProductBrandInfo;
import com.sls.game.pojo.SpecialPriceSystemInfo;
import com.sls.game.service.ProductBrandService;

/**
 * 
 * @description 产品品牌管理
 * @author Wangxuegang
 * @date 2012-9-13
 * 
 */
@Service("productBrandService")
public class ProductBrandServiceImpl implements ProductBrandService {

	private static Logger log = Logger.getLogger(ProductBrandServiceImpl.class);

	private Gson gson = null;

	public ProductBrandServiceImpl() {
		gson = CommonUtil.gson();
	}

	private ProductBrandDAO productBrandDAO;
	@Resource(name = "goodsInfoManageDAO")
	private GoodsInfoManageDAO goodsInfoManageDAO;
	@Resource(name = "goodsSupplyManageDAO")
	private GoodsSupplyManageDAO goodsSupplyManageDAO;
	@Resource(name = "specialPriceSystemDAO")
	private SpecialPriceSystemDAO priceSystemDAO;

	private OhFeiGoodsInfoDAO ohFeiGoodsInfoDAO;

	private NutsNetGoodsInfoDAO nutsNetGoodsInfoDAO;

	private TencentGoodsInfoDAO tencentGoodsInfoDAO;

	private OhFeiGoodsBrandDAO ohFeiGoodsBrandDAO;

	public OhFeiGoodsBrandDAO getOhFeiGoodsBrandDAO() {
		return ohFeiGoodsBrandDAO;
	}

	public void setOhFeiGoodsBrandDAO(OhFeiGoodsBrandDAO ohFeiGoodsBrandDAO) {
		this.ohFeiGoodsBrandDAO = ohFeiGoodsBrandDAO;
	}

	public OhFeiGoodsInfoDAO getOhFeiGoodsInfoDAO() {
		return ohFeiGoodsInfoDAO;
	}

	@Resource(name = "ohFeiGoodsInfoDAO")
	public void setOhFeiGoodsInfoDAO(OhFeiGoodsInfoDAO ohFeiGoodsInfoDAO) {
		this.ohFeiGoodsInfoDAO = ohFeiGoodsInfoDAO;
	}

	public NutsNetGoodsInfoDAO getNutsNetGoodsInfoDAO() {
		return nutsNetGoodsInfoDAO;
	}

	@Resource(name = "nutsNetGoodsInfoDAO")
	public void setNutsNetGoodsInfoDAO(NutsNetGoodsInfoDAO nutsNetGoodsInfoDAO) {
		this.nutsNetGoodsInfoDAO = nutsNetGoodsInfoDAO;
	}

	public TencentGoodsInfoDAO getTencentGoodsInfoDAO() {
		return tencentGoodsInfoDAO;
	}

	@Resource(name = "tencentGoodsInfoDAO")
	public void setTencentGoodsInfoDAO(TencentGoodsInfoDAO tencentGoodsInfoDAO) {
		this.tencentGoodsInfoDAO = tencentGoodsInfoDAO;
	}

	public ProductBrandDAO getProductBrandDAO() {
		return productBrandDAO;
	}

	@Resource(name = "productBrandDAO")
	public void setProductBrandDAO(ProductBrandDAO productBrandDAO) {
		this.productBrandDAO = productBrandDAO;
	}

	/**
	 * 分页查询
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryPageInquire(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}

		// 对消息body进行解析
		ProductBrandInfo pageInruire = gson.fromJson(body,
				ProductBrandInfo.class);
		boolean flag = checkDataOfQueryByPage(pageInruire, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				Pagination<ProductBrandInfo> paginationList = null;
				paginationList = productBrandDAO
						.queryPaginationList(pageInruire);

				String resultBody = null;
				if (paginationList != null) {
					resultBody = gson.toJson(paginationList);
				}

				log.info("分页查询结果为：  " + resultBody);
				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 品牌新增
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String insert(String body, Head head) throws ServerDisponseException {
		// 对消息body进行解析
		ProductBrandInfo productBrandInfo = gson.fromJson(body,
				ProductBrandInfo.class);
		boolean flag = checkDataOfInsert(productBrandInfo, head.getRequestId());
		if (flag) { // 数据校验通过
			// 新增品牌名称
			String brandName = productBrandInfo.getGameName();
			// 查询数据表
			String brandMaxIdStr = productBrandDAO.query();
			String brandId = "";
			if ("".equals(brandMaxIdStr) || brandMaxIdStr == null) {
				brandId = "100000000";
			} else {
				brandId = ObjectIncreaseId.increaseObjectId(brandMaxIdStr);
			}

			// 插入数据之前，判断该条记录是否存在
			boolean isExist = isExistOfBrand(brandName, "1");
			if (isExist) {
				ProductBrandInfo productBrandInfo1 = new ProductBrandInfo();
				productBrandInfo1.setId(UUID.randomUUID().toString());
				productBrandInfo1.setGoodsCategoryId(brandId);
				productBrandInfo1.setGameName(brandName);
				productBrandInfo1.setInitDisplay("1"); // 1表示门店加载时就显示 0表示否
				productBrandInfo1.setEnable("1"); // 1表示启用 0 表示禁用
				productBrandInfo1.setIsDelete("1"); // 0：表示删除，1：不删除
				productBrandInfo1.setRemark(productBrandInfo.getRemark());
				productBrandInfo1.setOperator(productBrandInfo.getOperator());
				productBrandInfo1.setHeat(productBrandInfo.getHeat());
				// 插入时间
				String now = ServerDateAndTime.getNowDateTimeOfFormat();
				productBrandInfo1.setInsertTime(now);

				try {
					productBrandDAO.insert(productBrandInfo1);
				} catch (Exception e) {
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
				return null;
			} else {
				throw new ServerDisponseException(
						ExceptionCodeDes.BRAND_RECORD_EXIST.getCode(),
						ExceptionCodeDes.BRAND_RECORD_EXIST.getDescription());
			}
		}

		return null;
	}

	/**
	 * 插入数据之前，判断该条记录是否存在
	 * 
	 * @param isDelete
	 * 
	 * @param productBrandInfo
	 * @return
	 */
	private boolean isExistOfBrand(String brandName, String isDelete) {
		boolean flag = false;
		List<ProductBrandInfo> productBrandInfo = null;
		ProductBrandInfo productBrandInfo2 = new ProductBrandInfo();
		productBrandInfo2.setGameName(brandName);
		productBrandInfo2.setIsDelete(isDelete);
		productBrandInfo = productBrandDAO.queryByBrandName(productBrandInfo2);
		if (productBrandInfo == null || productBrandInfo.isEmpty()) {
			flag = true;
		}

		return flag;
	}

	/**
	 * 品牌删除（假删除）
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String delete(String body, Head head) throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		ProductBrandInfo productBrandInfo = gson.fromJson(body,
				ProductBrandInfo.class);
		boolean flag = checkDataOfqueryById(productBrandInfo,
				head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				ProductBrandInfo productBrandInfo2 = new ProductBrandInfo();
				productBrandInfo2.setId(productBrandInfo.getId());
				productBrandInfo2.setIsDelete("0");
				// 更新记录的时间
				String now = ServerDateAndTime.getNowDateTimeOfFormat();
				productBrandInfo2.setModifyTime(now);
				productBrandInfo2.setOperator(productBrandInfo.getOperator());

				productBrandDAO.update(productBrandInfo2);
				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return null;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 品牌信息修改
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String update(String body, Head head) throws ServerDisponseException {
		// 对消息body进行解析
		ProductBrandInfo productBrandInfo = gson.fromJson(body,
				ProductBrandInfo.class);
		boolean flag = checkDataOfUpdate(productBrandInfo, head.getRequestId());
		if (flag) { // 数据校验通过
			try {
				String goodsCategoryId = productBrandInfo.getGoodsCategoryId();
				String brandName = productBrandInfo.getGameName();
				String operator = productBrandInfo.getOperator();
				ProductBrandInfo productBrand = productBrandDAO
						.queryById(goodsCategoryId);
				String oldBrandName = productBrand.getGameName();
				ProductBrandInfo productBrandInfo2 = new ProductBrandInfo();
				productBrandInfo2.setId(productBrandInfo.getId());
				productBrandInfo2.setGoodsCategoryId(goodsCategoryId);
				productBrandInfo2.setGameName(brandName);
				productBrandInfo2.setInitDisplay(productBrandInfo
						.getInitDisplay());
				productBrandInfo2.setEnable(productBrandInfo.getEnable());
				productBrandInfo2.setRemark(productBrandInfo.getRemark());
				productBrandInfo2.setOperator(operator);
				productBrandInfo2.setHeat(productBrandInfo.getHeat());
				// 更新的时间
				String now = ServerDateAndTime.getNowDateTimeOfFormat();
				productBrandInfo2.setModifyTime(now);
				productBrandDAO.update(productBrandInfo2);
				if (!oldBrandName.equals(brandName)) {

					GoodsManageInfo goodsManageInfo = new GoodsManageInfo();
					goodsManageInfo.setBrandName(brandName);
					goodsManageInfo.setGoodsCategoryId(goodsCategoryId);
					goodsManageInfo.setModifyTime(now);
					goodsManageInfo.setOperator(operator);
					this.goodsInfoManageDAO.updateByBrandId(goodsManageInfo);

					GoodsSupplyManageInfo supplyManageInfo = new GoodsSupplyManageInfo();
					supplyManageInfo.setBrandName(brandName);
					supplyManageInfo.setGoodsCategoryId(goodsCategoryId);
					supplyManageInfo.setModifyTime(now);
					supplyManageInfo.setOperator(operator);
					this.goodsSupplyManageDAO.updateByBrandId(supplyManageInfo);

					SpecialPriceSystemInfo priceSystemInfo = new SpecialPriceSystemInfo();
					priceSystemInfo.setBrandName(brandName);
					priceSystemInfo.setBrandId(goodsCategoryId);
					priceSystemInfo.setModifyTime(now);
					priceSystemInfo.setOperator(operator);
					this.priceSystemDAO.updateByBrandId(priceSystemInfo);

				}

				return null;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！", e);
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 根据品牌Id值，查询该品牌记录
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryByBrandId(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		ProductBrandInfo productBrandInfo = gson.fromJson(body,
				ProductBrandInfo.class);
		boolean flag = checkDataOfqueryByBrandId(productBrandInfo,
				head.getRequestId());

		if (flag) { // 数据校验通过
			try {
				String resultBody = null;
				String goodsCategoryId = productBrandInfo.getGoodsCategoryId();
				ProductBrandInfo productBrandInfo1 = null;
				productBrandInfo1 = productBrandDAO.queryById(goodsCategoryId);

				if (productBrandInfo1 != null) {
					resultBody = gson.toJson(productBrandInfo1);
				}

				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 数据校验
	 */
	private boolean checkDataOfQueryByPage(ProductBrandInfo pageInruire,
			String reqId) throws ServerDisponseException {
		boolean flag = false;
		// 当前页
		String pageIndex = pageInruire.getCurrentPage() + "";
		// 每页显示记录数
		String pageSize = pageInruire.getPageSize() + "";

		if ("".equals(pageIndex) || pageIndex == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.CURRENT_PAGE_NULL.getCode(),
					ExceptionCodeDes.CURRENT_PAGE_NULL.getDescription());
		} else if ("".equals(pageSize) || pageSize == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PAGE_SIZE_NULL.getCode(),
					ExceptionCodeDes.PAGE_SIZE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 数据校验
	 */
	private boolean checkDataOfInsert(ProductBrandInfo productBrandInfo,
			String reqId) throws ServerDisponseException {
		boolean flag = false;

		// 操作员账号
		String operator = productBrandInfo.getOperator();

		if ("".equals(operator) || operator == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.OPERATOR_NO_NULL.getCode(),
					ExceptionCodeDes.OPERATOR_NO_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * @param productBrandInfo
	 * @param reqId
	 * @return
	 * @throws ServerDisponseException
	 */
	private boolean checkDataOfqueryById(ProductBrandInfo productBrandInfo,
			String reqId) throws ServerDisponseException {
		boolean flag = false;
		String id = productBrandInfo.getId();
		if (StringUtils.isEmpty(id)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ID_EMPTY.getCode(),
					ExceptionCodeDes.ID_EMPTY.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 数据校验
	 */
	private boolean checkDataOfqueryByBrandId(
			ProductBrandInfo productBrandInfo, String reqId)
			throws ServerDisponseException {
		boolean flag = false;
		String goodsCategoryId = productBrandInfo.getGoodsCategoryId();
		if ("".equals(goodsCategoryId) || goodsCategoryId == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.BRAND_ID_NULL.getCode(),
					ExceptionCodeDes.BRAND_ID_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 数据校验
	 */
	private boolean checkDataOfUpdate(ProductBrandInfo productBrandInfo,
			String reqId) throws ServerDisponseException {
		boolean flag = false;
		String goodsCategoryId = productBrandInfo.getGoodsCategoryId();
		// 游戏名称
		String gameName = productBrandInfo.getGameName();
		// 初始化显示
		String initDisplay = productBrandInfo.getInitDisplay();
		// 是否启用
		String enable = productBrandInfo.getEnable();

		if ("".equals(goodsCategoryId) || goodsCategoryId == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.BRAND_ID_NULL.getCode(),
					ExceptionCodeDes.BRAND_ID_NULL.getDescription());
		} else if ("".equals(gameName) || gameName == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.BRAND_NAME_NULL.getCode(),
					ExceptionCodeDes.BRAND_NAME_NULL.getDescription());
		} else if ("".equals(initDisplay) || initDisplay == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.INIT_DISPLAY_NULL.getCode(),
					ExceptionCodeDes.INIT_DISPLAY_NULL.getDescription());
		} else if ("".equals(enable) || enable == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.IS_ENABLE_NULL.getCode(),
					ExceptionCodeDes.IS_ENABLE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 查询该操作员，新增的品牌编号
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 * @date 2012-09-24
	 */
	@Override
	public String queryNewBrandId(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		ProductBrandInfo productBrandInfo = gson.fromJson(body,
				ProductBrandInfo.class);
		boolean flag = checkDataOfQueryNewBrandId(productBrandInfo,
				head.getRequestId());
		if (flag) {
			try {
				String resultBody = null;
				String brandId = null;
				brandId = productBrandDAO.queryNewBrandId(productBrandInfo);
				if (brandId != null) {
					resultBody = gson.toJson(brandId);
				}

				if (log.isInfoEnabled()) {
					log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
				}
				return resultBody;
			} catch (Exception e) {
				log.error("Service处理[" + head.getRequestId() + "]的请求出现异常！");
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}

		return null;
	}

	/**
	 * 数据校验
	 */
	private boolean checkDataOfQueryNewBrandId(
			ProductBrandInfo productBrandInfo, String reqId)
			throws ServerDisponseException {
		boolean flag = false;
		String operator = productBrandInfo.getOperator();
		if ("".equals(operator) || operator == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.OPERATOR_NO_NULL.getCode(),
					ExceptionCodeDes.OPERATOR_NO_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

}
